<?php

class ProductController extends MainController implements ControllerInterface {

	public $tableConfig = array(
		'product_table' => array(
			'o' => array(
				'id' => 'product.id_product',
				'code' => 'product.code',
				'name' => 'product_description.name',
				'_' => 'id'
			),
			'v' => 'malejaco',
			't' => 10
		),
		'infopts_table' => array(
			'o' => array(
				'id' => 'image_map.id_image_map',
				'name' => 'image_map_description.title',
				'_' => 'id'
			),
			'v' => 'malejaco',
			't' => 2
		)
	);

	/**
	 * Strona glowna
	 *
	 */
	public function IndexAction($param) {
		$this->AddDescription("");
		$this->AddTitle("");
	}

	/**
	 * Widok Produktu
	 *
	 */
	public function ViewAction($param) {
		
		$this->AddScript('jquery.lightbox-0.5.js', 'file', 'top', 9);
		$this->AddScript('jquery.rating.pack.js', 'file', 'top');
		$this->AddScript('jquery.MetaData.js', 'file', 'top');
		$this->AddScript('jquery-ui-1.8.16.custom.min.js', 'file', 'top');
		$this->AddScript('jquery-validate/additional-methods.js', 'file', 'top');
		
		$this->addStyle(URL_STATIC_CONTENT . '/css/jquery.lightbox-0.5.css');
		$this->addStyle(URL_STATIC_CONTENT . '/css/jquery.rating.css');
		$this->addStyle(URL_STATIC_CONTENT . '/css/jquery-ui-1.7.1.custom.css');
//		$this->addStyle(URL_STATIC_CONTENT . '/css/ui.slider.extras.css');
		try {
			
			$productsIds = SessionProxy::GetValue('__products__ids__', null);
			if(!empty($productsIds))
			{
				SessionProxy::ClearValue('__products__ids__');
			}			

			SessionProxy::ClearValue('__product_list_selected_properties__');
			SessionProxy::ClearValue('__product_list_selected_companies__');

			//$this->AddDescription("");
			//$this->AddTitle("");


			$productObj = $this->GetProduct(array('value' => $param['productKey']));

			if (!is_object($productObj)) {
				throw new UserException('No Product');
			}

			$id = $productObj->getId();

			$dalObjr = ProductRankingDAL::GetDalDataObj();
			$dalObjr->addCondition('product_ranking.id_product', $productObj->getId());
			$dalObjr->addJoin('ProductRankingType', ' LEFT JOIN product_ranking_type ON (product_ranking.type=product_ranking_type.id_product_ranking_type AND product_ranking_type.active = 1) ');
			$productRanking = ProductRankingDAL::GetResult($dalObjr);

			$this->smarty->assign('productRanking', $productRanking);


			$productObj->productRanking = $productRanking;

			$dalObj = ProductVotesRankingDAL::GetDalDataObj();
			$dalObj->addJoin('ProductVotesType', ' JOIN product_votes_type on ( product_votes_type.id_product_votes_type = product_votes_ranking.id_product_votes_type ) ');
			$dalObj->addCondition('id_product', $productObj->getId());

			$productVotes = ProductVotesRankingDAL::GetResult($dalObj);

			$productObj->productVotes = $productVotes;

			$this->smarty->assign('productVotes', $productVotes);



			$this->smarty->assign('obj', $productObj);
			
			$dalDataC = CategoryDAL::GetDalDataObj();
			$dalDataC->setId($productObj->getIdCategory());
			$category = CategoryDAL::GetById($dalDataC);
			
			$dalObj = PropertyValueDAL::GetDalDataObj();
			$dalObj->addCondition('id_product', $productObj->getId());
			$dalObj->addJoin('Property', ' JOIN property ON (property_value.id_product = ' . $productObj->getId() . ' AND property_value.id_property = property.id_property AND property.active = 1) ');
			$dalObj->addJoin('PropertyDescription', ' LEFT JOIN property_description ON(property.id_property = property_description.id_property AND property_description.id_language = ' . Registry::Get('default_language_id') . ')');
			// $dalObj->setGroupBy('property.id_property');
			 $dalObj->addCondition('property.id_property_group', '6');
			 $dalObj->addCondition('(property.id_category', $productObj->getIdCategory());
			 $dalObj->addCondition('property.id_category', $category->getParent(), ' = ', ' OR ');
			 $dalObj->addCondition('1', 1, ' = ', ') AND');
			 $dalObj->setOrderBy('property.position ASC');
			 //$dalObj->addCondition('property_value.type', Registry::Get('METRIC_SYSTEM_TYPE'));
			 $properties10 = PropertyValueDAL::GetResult($dalObj);
			 
			 $properties1 = array();
			 foreach($properties10 as $prop) {
				 if(!isset($properties1[$prop->property->getId()]))
				 $properties1[$prop->property->getId()] = $prop;
				 else
					 $properties1[$prop->property->getId()]->setValue2($prop);
			 }
//var_dump($properties1);
			 $dalObj = PropertyValueDAL::GetDalDataObj();
			 $dalObj->addCondition('id_product', $productObj->getId());
			 $dalObj->addJoin('Property', ' JOIN property ON (property_value.id_product = '.$productObj->getId().' AND property_value.id_property = property.id_property AND property.active = 1) ');
			 $dalObj->addJoin('PropertyDescription', ' LEFT JOIN property_description ON(property.id_property = property_description.id_property AND property_description.id_language = '.Registry::Get('default_language_id').')');
			 //$dalObj->setGroupBy('property.id_property');
			 $dalObj->addCondition('property.id_property_group', '7');
			 $dalObj->addCondition('(property.id_category', $productObj->getIdCategory());
			 $dalObj->addCondition('property.id_category', $category->getParent(), ' = ', ' OR ');
			 $dalObj->addCondition('1', 1, ' = ', ') AND');
			 $dalObj->setOrderBy('property.position ASC');
			 //$dalObj->addCondition('property_value.type', Registry::Get('METRIC_SYSTEM_TYPE'));
			 $properties20 = PropertyValueDAL::GetResult($dalObj);
			 $properties2 = array();
			 foreach($properties20 as $prop) {
				 if(!isset($properties2[$prop->property->getId()]))
				 $properties2[$prop->property->getId()] = $prop;
				 else
					 $properties2[$prop->property->getId()]->setValue2($prop);
			 }

			 $dalObj = PropertyValueDAL::GetDalDataObj();
			 $dalObj->addCondition('id_product', $productObj->getId());
			 $dalObj->addJoin('Property', ' JOIN property ON (property_value.id_product = '.$productObj->getId().' AND property_value.id_property = property.id_property AND property.active = 1) ');
			 $dalObj->addJoin('PropertyDescription', ' LEFT JOIN property_description ON(property.id_property = property_description.id_property AND property_description.id_language = '.Registry::Get('default_language_id').')');
			 //$dalObj->setGroupBy('property.id_property');
			 $dalObj->addCondition('property.id_property_group', '5');
			 $dalObj->addCondition('(property.id_category', $productObj->getIdCategory());
			 $dalObj->addCondition('property.id_category', $category->getParent(), ' = ', ' OR ');
			 $dalObj->addCondition('1', 1, ' = ', ') AND');
			 $dalObj->setOrderBy('property.position ASC');
			 //$dalObj->addCondition('property_value.type', Registry::Get('METRIC_SYSTEM_TYPE'));
			 $properties50 = PropertyValueDAL::GetResult($dalObj);

			/*$dalObj = PropertyValueDAL::GetDalDataObj();
			$dalObj->addCondition('id_product', $productObj->getId());
			$dalObj->addJoin('Property', ' JOIN property ON (property_value.id_product = ' . $productObj->getId() . ' AND property_value.id_property = property.id_property AND property.active = 1) ');
			$dalObj->addJoin('PropertyDescription', ' LEFT JOIN property_description ON(property.id_property = property_description.id_property AND property_description.id_language = ' . Registry::Get('default_language_id') . ')');
			//$dalObj->setGroupBy('property.id_property');
			$dalObj->addCondition('property.id_property_group', '5');
			//$dalObj->addCondition('property_value.type', Registry::Get('METRIC_SYSTEM_TYPE'));
			$properties50 = PropertyValueDAL::GetResult($dalObj);*/

			$properties5 = array();
			foreach ($properties50 as $prop) {
				if (!isset($properties5[$prop->property->getId()]))
					$properties5[$prop->property->getId()] = $prop;
				else
					$properties5[$prop->property->getId()]->setValue2($prop);
			}

			$this->smarty->assign('properties1', $properties1);
			$this->smarty->assign('properties2', $properties2);
			$this->smarty->assign('properties5', $properties5);

			$this->smarty->assign('subCategoryKey', $param['subCategoryKey']);
			$this->smarty->assign('categoryKey', $param['categoryKey']);

			$dalObj = CategoryDAL::GetDalDataObj();
			$dalObj->addCondition('category.id_category', $productObj->getIdCategory());
			$dalObj->addJoin('CategoryDescription', ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = 1)');
			$category = CategoryDAL::GetResult($dalObj);
			$this->smarty->assign('category', $category[0]);



			$dalObj = CategoryDAL::GetDalDataObj();
			$dalObj->addCondition('category.id_category', $category[0]->getParent());
			$dalObj->addJoin('CategoryDescription', ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = 1)');
			$categoryP = CategoryDAL::GetResult($dalObj);
			$this->smarty->assign('categoryParent', $categoryP[0]);

			$this->AddBreadCrumb($categoryP[0]->getCategoryDescription()->getName(), null);

			$this->AddBreadCrumb($category[0]->getCategoryDescription()->getName(), Router::GenerateUrl('mainCategoryView', array('subCategoryKey' => $category[0]->getSlug(), 'categoryKey' => $categoryP[0]->getSlug())));

			$this->AddBreadCrumb($productObj->getProductDescription()->getName(), Router::GenerateUrl('productView', array('categoryKey' => $category[0]->getSlug(), 'subCategoryKey' => $categoryP[0]->getSlug(), 'productKey' => $productObj->getSlug())));

			$this->AddTitle($productObj->getProductDescription()->getName());
			$this->AddDescription($productObj->getProductDescription()->getSeoDescription());
			$this->AddKeywords($productObj->getProductDescription()->getSeoKeywords());

			$dalObj = ProductImageDAL::GetDalDataObj();
			$dalObj->addCondition('active', '1');
			$dalObj->addCondition('id_product', $productObj->getId());
			$images = ProductImageDAL::GetResult($dalObj);

			$this->smarty->assign('images', $images);

			$dalObj = ProductVideoDAL::GetDalDataObj();
			$dalObj->addCondition('active', '1');
			$dalObj->addCondition('id_product', $productObj->getId());
			$dalObj->setOrderBy('id_product_video DESC');
			$videos = ProductVideoDAL::GetResult($dalObj);

			$this->smarty->assign('videos', $videos);

			$dalObjm = ImageMapDAL::GetDalDataObj();
			$dalObjm->addCondition('id_product', $id);
			$dalObjm->addCondition('active', '1');
			$dalObjm->addJoin('ImageMapDescription', ' LEFT JOIN image_map_description ON (image_map.id_image_map = image_map_description.id_image_map AND image_map_description.id_language = 1)');
			$imageMap = ImageMapDAL::GetResult($dalObjm);

			$this->smarty->assign('map', $imageMap);

			$settings = array(
				'condition' => array(
					'id_category' => array($productObj->getIdCategory()),
					'active' => array(1)));
			$dalData = ProductVotesTypeDAL::GetDalDataObj($settings);

			$commentsObj = new Comments();
			$comments = $commentsObj->GetComments(1, $productObj->getId());
			$userCanComment = true;
			foreach($comments as $item) {
				if(is_object($this->user))
				if($item->getIdUser() == $this->user->getId()){
					$userCanComment = false;
					break;
				}
			}

			$comments = $this->SerializeComments($comments);
			
			unset($commentsObj);
			
			if (is_object($this->user)) {
				$userEq = new UserEquipment();
				$ineq = $userEq->isProductInEq($productObj->getId(), $this->user->getId());
				$prodTypeineq = $userEq->isProductTypeInEq($productObj, $this->user->getId());
				$userEq = $userEq->GetUserEq($this->user->getId());
				$this->smarty->assign('prod_type_eq', $prodTypeineq);
				$this->smarty->assign('prod_in_eq', $ineq);
			} else {
				$userEq = array();
			}

			$this->AddScript('jquery-validate/jquery.validate.js');
			$this->AddScript(Router::GenerateUrl('opinionValidation') . '?id_f=fr-opinion');
			
			
			$this->smarty->assign('userCanComment', $userCanComment);
			$this->smarty->assign('comments', $comments);
			$this->smarty->assign('vote', ProductVotesTypeDAL::GetResult($dalData));
			$this->smarty->assign('lang_id', Registry::Get('default_language_id'));

			$userEquipement = UserEquipmentDAL::GetDalDataObj(array(
				'condition' => array(
					'id_product' => $productObj->getId()
				),
				'join' => array(
					'User' => ' LEFT JOIN user USING(id_user)'
				)
			));

			if($this->userLoggedIn) {
				$userEquipement->addCondition('id_user',$this->user->getId(),' != ');
			}

			$this->smarty->assign('othersEquipment', UserEquipmentDAL::GetResult($userEquipement));
			

		} catch (UserException $e) {
			$this->AddDescription("");
			$this->AddTitle("");
			//var_dump($e);
			$this->AddRedirectInfo('', 'error', Router::GenerateUrl('default'));
			$this->SetNoRender();
		}
	}
	
	public function SaveCommentAction($param) {
		try {
			$this->SetNoRender();
			if (Request::IsPost()) {
				$this->addComment($param);
				$cfgModeration = Config::Get('comments_moderation');
				$status = !empty($cfgModeration[0]) ? 1 : 0;
				if ($status) {
					$msg = $this->T('Premoderation is active');
				} else {
					$msg = $this->T('Your comment has been added.');
				}

				$product = new Product();
				$this->AddRedirectInfo($msg, 'ok', $product->getProductHref(Request::GetPost('id')) . '#useropinions');
			}
		} catch (Exception $e) {
			
		}
	}
	
	public function OpinionValidationAction($param, $as_action = true) {	
		if ($as_action)
				$param['validation_data'] = array();	
		
		$validator = new Validator($param['validation_data']);
		$validator->notEqual('opinion_title', 'enter text...', 'Please enter title');
		$validator->IsLonger('opinion_title', 90, 'Maximum 90 charcters');
		$validator->notEqual('opinion_content', 'enter text...', 'Please enter opinion');
		$validator->IsLonger('opinion_content', 3000, 'Maximum 3000 charcters');
		
		$this->smarty->assign('js_values', $validator->getJsValues());
		$this->smarty->assign('id_form', Request::GetGet('id_f'));
		
		return $validator->getErrorList();
	}
	
	private function SerializeComments($obj, $filter_vars = '') {
		$arrMinMax = array();
		if (!empty($filter_vars)) {
			foreach ($filter_vars as $item) {
				$tmp = explode('|', $item);
				$arrMinMax[$tmp[0]] = array('min' => ceil($tmp[1] / 10), 'max' => ceil($tmp[2] / 10));
			}
		}

		$serialize = array();
		$trash = array();
		foreach ($obj as $item) {
			$parent = $item->getIdParent();
			$id = $item->getId();
			if (!empty($parent)) {
				$serialize[$parent]['subComments'][] = $item;
			} else {
				$serialize[$id]['parent'] = $item;

				$dalObj = ProductVotesDAL::GetDalDataObj();
				$dalObj->addJoin('ProductVotesType', 'LEFT JOIN product_votes_type ON product_votes_type.id_product_votes_type = product_votes.id_product_votes_type');
				$dalObj->addCondition('id_comments', $item->getId());

				$serialize[$id]['votes'] = ProductVotesDAL::GetResult($dalObj);
				foreach ($serialize[$id]['votes'] as $item) {
					$idType = $item->getIdProductVotesType();
					if (isset($arrMinMax[$idType])) {
						if ($item->getRate() < $arrMinMax[$idType]['min']) {
							$trash[] = $id;
						} else if ($item->getRate() > $arrMinMax[$idType]['max']) {
							$trash[] = $id;
						}
					} else {
//						$trash[] = $id;
					}
				}
			}
		}
		//wywalam nie potrzebne komenty
		foreach ($trash as $item) {
			unset($serialize[$item]);
		}
		return $serialize;
	}

	private function GetProduct($condition) {
		try {
			$productObj = ProductDAL::GetResult(ProductDAL::GetDalDataObj(array(
								'tableData' => $this->tableParams['product_table'],
								'join' => array(
									'ProductDescription' => ' LEFT JOIN product_description ON(product.id_product = product_description.id_product AND product_description.id_language = ' . Registry::Get('default_language_id') . ')',
									'Manufacturer' => ' JOIN manufacturer ON (product.id_manufacturer = manufacturer.id_manufacturer AND manufacturer.active = 1)'
								),
								'condition' => array('product.slug' => array($condition['value']), 'product.active' => array('1'))
							)));
			if (is_array($productObj) && isset($productObj[0])) {
				$productObj = $productObj[0];

				$dalObj = PropertyDAL::GetDalDataObj();
				$dalObj->addJoin('PropertyValue', ' LEFT JOIN property_value ON (property_value.id_property = property.id_property) ');
				$dalObj->addJoin('PropertyDescription', ' LEFT JOIN property_description ON(property.id_property = property_description.id_property AND property_description.id_language = ' . Registry::Get('default_language_id') . ')');
				$dalObj->addCondition('active', '1');
				$dalObj->addCondition('property_value.id_product', $productObj->getId());
				$dalObj->addCondition('property_value.type', Registry::Get('METRIC_SYSTEM_TYPE'));
				// $dalObj->addCondition('property.id_property_group', '6');
				$dalObj->setGroupBy('property.id_property');
				$properties1 = PropertyDAL::GetResult($dalObj);

				$dalObj = PropertyDAL::GetDalDataObj();
				$dalObj->addJoin('PropertyValue', ' LEFT JOIN property_value ON (property_value.id_property = property.id_property) ');
				$dalObj->addJoin('PropertyDescription', ' LEFT JOIN property_description ON(property.id_property = property_description.id_property AND property_description.id_language = ' . Registry::Get('default_language_id') . ')');
				$dalObj->addCondition('active', '1');
				$dalObj->addCondition('property_value.id_product', $productObj->getId());
				$dalObj->addCondition('property_value.type', Registry::Get('METRIC_SYSTEM_TYPE'));
				// $dalObj->addCondition('property.id_property_group', '7');
				$dalObj->setGroupBy('property.id_property');
				$properties2 = PropertyDAL::GetResult($dalObj);
			} else {
				return false;
			}


			return $productObj;
		} catch (Exception $e) {
			$this->AddRedirectInfo($this->T('No product'));
		}
	}


	/**
	 * Zwraca ip osoby odwiedzajacej strone
	 * @return type 
	 */
	private function getIp() {
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		} else {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
		return $ip;
	}

	public function ajaxReportAbuseCommentAction($param) {
		header('Content-type: application/javascript');
		$this->SetAjaxRender();
		$this->SetNoRender();

		try {
			$this->smarty->assign('comment_abuse_id', $param['id']);
			$ret = $this->smarty->fetch('partial/Product/ReportAbuse.tpl');
			echo json_encode($ret);
		} catch (Exception $e) {
			
		}
	}

	public function ajaxSaveAbuseCommentAction($param) {
		header('Content-type: application/javascript');
		$this->SetAjaxRender();
		$this->SetNoRender();
		try {
			$reason = Request::Get('reason');
			$cAbuse = new CommentsAbuse();
			$cAbuse->setIdComments($param['id']);
			$cAbuse->setIdUser($this->user->getId());
			$cAbuse->setReason($reason);
			CommentsAbuseDAL::Save($cAbuse->GetDalDataObj());
			echo json_encode($this->t('We have received your report abuse.'));
		} catch (Exception $e) {
			
		}
	}

	public function ajaxFilterCommentAction($param) {
		header('Content-type: application/javascript');
		$this->SetAjaxRender();
		$this->SetNoRender();
		try {
			$var = Request::GetPost('var');
			$custom = Request::GetPost('custom');
			$filter = array();
			if (!empty($var)) {
				$arrData = explode(',', $var);

				foreach ($arrData as $item) {
					if ((int) $item > 0) {
						$filter['custom']['age'][] = $item;
					} else {
						$filter['custom']['gender'][] = $item;
					}
				}
			}
			$filter['custom']['order'] = Request::GetPost('order');

			$arrData = array();
			if (!empty($custom)) {
				$arrData = explode(',', $custom);
			}
			$arrData[] = $filter;

			$comments = new Comments();

			$arrComments = $comments->GetComments(1, $param['id'], $arrData);
//		$arrComments = $this->GetProductComments($param['id'], $filter, $arrData);
			$this->smarty->assign('comments', $this->SerializeComments($arrComments));

			$ret = $this->smarty->fetch('partial/Product/CommentsList.tpl');
			echo $ret;
		} catch (Exception $e) {
			
		}
	}

	public function ajaxRateCommentAction($param) {
		header('Content-type: application/javascript');
		$this->SetAjaxRender();
		$this->SetNoRender();
		$comments = new Comments();
		$comments->setId($param['id']);

		if ($this->userLoggedIn) {
			if (!$comments->userCantRateComment()) {
				if ($param['action'] == 'like') {
					$comments->addLike();
					$date = date('Y-m-d H:i:s');
					$this->RunShared('addActivityPoints', array(
						'action' => 'USER_COMMENT_RATING',
						'idUser' => $this->user->getId(),
						'tpl_vars' => array(
							'%user_first_name%' => $this->user->getFirstName(),
							'%user_last_name%' => $this->user->getLastName(),
							'%activity_timestamp%' => $date
						)
					));
					echo 'LIKE';
				} else if ($param['action'] == 'dislike') {
					$comments->addDisLike();
					$date = date('Y-m-d H:i:s');
					$this->RunShared('addActivityPoints', array(
						'action' => 'USER_COMMENT_RATING',
						'idUser' => $this->user->getId(),
						'tpl_vars' => array(
							'%user_first_name%' => $this->user->getFirstName(),
							'%user_last_name%' => $this->user->getLastName(),
							'%activity_timestamp%' => $date
						)
					));
					echo 'DISLIKE';
				}
			} else {
				echo 'CANT_RATE';
			}
		} else {
			echo 'NOT_LOGGED';
		}
	}

	/**
	 * 'maly' komentarz
	 * @param type $param 
	 */
	public function ajaxAddCommentAction($param) {
		header('Content-type: application/javascript');
		$this->SetAjaxRender();
		$this->SetNoRender();

		if (Request::IsPost() && $this->userLoggedIn) {
			$parent = Request::GetPost('parent', true);
			$content = Request::GetPost('comment', true);
			$idProduct = Request::GetPost('product', true);
			$date = date('Y-m-d H:i:s');

			$cfgModeration = Config::Get('comments_moderation');
			$status = !empty($cfgModeration[0]) ? 1 : 0;
				
			if($this->RunShared('BadWords', $post['opinion_content'])) {
				$status = 0; //wyryto zakazane slowa dlatego ustawiamy status na nieaktywny
			}
				
			$comment = new Comments();
			$comment->setIdParent($parent);
			$comment->setContent($content);
			$comment->setDate($date);
			$comment->setActive($status);
			$comment->setType(1);
			$comment->setIdContent($idProduct);
			$comment->setIdUser($this->user->getId());
			$comment->setNew(1);
		
			$product = new Product();
			$product_href = $product->getProductHref($idProduct);
			$product_name = $product->getProductName($idProduct);


			$idComments = CommentsDAL::Save($comment->GetDalDataObj());
			$this->RunShared('addActivityPoints', 
					array(
						'action' => 'PRODUCT_RATING', 
						'idUser' => $this->user->getId(),
						'tpl_vars' => array(
							'%user_first_name%' => $this->user->getFirstName(),
							'%user_last_name%' => $this->user->getLastName(),
							'%activity_timestamp%' => $date,
							'%link_href%' => $product_href,
							'%link_title%' => $product_name
						)
					));

			$this->smarty->assign('content', $content);
			$html = $this->smarty->fetch('partial/Product/NewOpinionComment.tpl');
			echo json_encode($html);
		}
	}

	private function addComment($param) {
		if ($this->userLoggedIn) {
			try {
				$post = Request::GetAllPost();
				$comment = new Comments();
				
				$cfgModeration = Config::Get('comments_moderation');
				$status = !empty($cfgModeration[0]) ? 1 : 0;
				
				if($this->RunShared('BadWords', $post['opinion_content'])) {
					$status = 0; //wyryto zakazane slowa dlatego ustawiamy status na nieaktywny
				}
				$arrData = array(
					'idProduct' => $post['id'],
					'title' => $post['opinion_title'],
					'content' =>$post['opinion_content'],
					'user' => $this->user,
					'type' => 1,
					'status' => $status
				);
				
				$idComments = $comment->addComment($arrData);
				if($idComments > 0) {
					$this->smarty->assign('moderation_on', 1);
				}
				//zapis ocen czastkowych
				if(isset($post['star']))
				foreach ($post['star'] as $key => $value) {
					$vote = new ProductVotes();
					$vote->setIdProduct($arrData['idProduct']);
					$vote->setIdComments($idComments);
					$vote->setDate(date('Y-m-d H:i:s'));
					$vote->setIp($comment->getIp());
					$vote->setIdProductVotesType($key);
					$vote->setRate($value);

					ProductVotesDAL::Save($vote->GetDalDataObj());
				}
				
				$product = new Product();
				$product_href = $product->getProductHref($arrData['idProduct']);
				$product_name = $product->getProductName($arrData['idProduct']);
				$this->RunShared('addActivityPoints', 
					array(
						'action' => 'PRODUCT_RATING_FIRST', 
						'idUser' => $this->user->getId(),
						'tpl_vars' => array(
							'%user_first_name%' => $this->user->getFirstName(),
							'%user_last_name%' => $this->user->getLastName(),
							'%link_href%' => $product_href,
							'%link_title%' => $product_name
						)
					));
				
			} catch (Exception $e) {
				$this->AddDescription("");
				$this->AddTitle("");
				$this->AddRedirectInfo($this->T('productNewComment'), 'error', Router::GenerateUrl('default'));
				$this->SetNoRender();
//				var_dump($e->getMessage());
			}
		}
	}

	public function CompareAction($param) {
		//$this->AddDescription("");
		//$this->AddTitle("");

		$this->smarty->assign('listOfProducts', $param['listOfProducts']);

		if (isset($param['listOfProducts'])) {
			$productsArray = explode('_', $param['listOfProducts']);
			$x = 0;
			foreach ($productsArray as $pk) {
				if ($pk == '') {
					unset($productsArray[$x]);
				}
				$x++;
			}

			$dalObj = ProductDAL::GetDalDataObj();
			$dalObj->addCondition('product.id_product', '("' . implode('","', $productsArray) . '")', ' IN ');
			$dalObj->addJoin('ProductDescription', ' LEFT JOIN product_description ON(product.id_product = product_description.id_product AND product_description.id_language = ' . Registry::Get('default_language_id') . ')');
			$dalObj->addJoin('Manufacturer', ' LEFT JOIN manufacturer ON (product.id_manufacturer = manufacturer.id_manufacturer AND manufacturer.active = 1)');
			$products = ProductDAL::GetResult($dalObj);


			$dalObj = PropertyDAL::GetDalDataObj();
			$dalObj->addJoin('PropertyValue', ' LEFT JOIN property_value ON (property_value.id_property = property.id_property) ');
			$dalObj->addJoin('PropertyDescription', ' LEFT JOIN property_description ON(property.id_property = property_description.id_property AND property_description.id_language = ' . Registry::Get('default_language_id') . ')');
			$dalObj->addCondition('active', '1');
			$dalObj->addCondition('property_value.id_product', ' ("' . implode('","', $productsArray) . '") ', ' IN ');
			$dalObj->addCondition('property_value.type', Registry::Get('METRIC_SYSTEM_TYPE'));
			$dalObj->setGroupBy('property.id_property');
			$properties = PropertyDAL::GetResult($dalObj);
	

			foreach ($products as $product) {
				$dalObj = PropertyValueDAL::GetDalDataObj();
				$dalObj->addCondition('id_product', $product->getId());
				$dalObj->addJoin('Property', ' JOIN property ON (property_value.id_product = ' . $product->getId() . ' AND property_value.id_property = property.id_property AND property.active = 1) ');
				$dalObj->addJoin('PropertyDescription', ' LEFT JOIN property_description ON(property.id_property = property_description.id_property AND property_description.id_language = ' . Registry::Get('default_language_id') . ')');
				$dalObj->setGroupBy('property.id_property');
				$product->setProperties(PropertyDAL::GetResult($dalObj));
			}
		}

		// drobna zmiana przy generowaniu tabelek

		$_rowsMaxLength = array(
			0, 0, 0, 0, 0
		);
		
		$_i = 5;

		$_tableData = array(
			array(0 => '&nbsp;'),
			array(0 => 'Product name'),
			array(0 => 'Brand name'),
			array(0 => 'Popularity'),
			array(0 => 'Rate')
		);

		$_var_config_arr = array();
		
		foreach ($properties as $item) {
			$_tableData[$_i] = array(0 => $item->getPropertyDescription()->getDescription());
			$_var_config_arr[$item->getId()] = $_i;
			$_i += 1;
		}
		$_tableData[$_i] = array('Price');
		
		$pc = 1;
		$productsArray = array(0 => null);
		foreach ($products as $_product) {
			$productsArray[$pc] = $_product;
			$_tableData[0][$pc] = $product->getMainImage();
			$_svar = $_product->getProductDescription()->getName();
			$_tableData[1][$pc] = $_svar;
			$_rowsMaxLength[1] = (mb_strlen($_svar) > $_rowsMaxLength[1]?mb_strlen($_svar):$_rowsMaxLength[1]);
			$_svar = $_product->getManufacturer()->getName();
			$_tableData[2][$pc] = $_svar;
			$_rowsMaxLength[2] = (mb_strlen($_svar) > $_rowsMaxLength[2]?mb_strlen($_svar):$_rowsMaxLength[2]);
			$_tableData[3][$pc] = $_product->getPopularity();
			$_tableData[4][$pc] = $_product->getRate();
			
			for($ii = 5; $ii <= $_i; $ii++)
			{
				$_tableData[$ii][$pc] = null;
			}
			
			$_j = 5;
			foreach ($_product->getProperties() as $_property) {
				$_svar = $_property->getPrepend() . ' ' . $_property->getValue() . ' ' . $_property->getAppend();
				$_tableData[$_var_config_arr[$_property->getIdProperty()]][$pc] = $_svar;
				if(!isset($_rowsMaxLength[$_j])) $_rowsMaxLength[$_j] = 0;
				$_rowsMaxLength[$_j] = (mb_strlen($_svar) > $_rowsMaxLength[$_j]?mb_strlen($_svar):$_rowsMaxLength[$_j]);
				$_j += 1;
			}
			$_tableData[$_i][$pc] = '€80';
			$pc += 1;
		}


		$this->smarty->assign('tableData', $_tableData);
		$this->smarty->assign('_rowsMaxLength', $_rowsMaxLength);
		$this->smarty->assign('productsArray', $productsArray);

		$this->smarty->assign('specialClasses', array(0 => 'thumb', 1 => 'title', 2 => 'brand', 3 => 'popularity', 4 => 'rate', $_i => 'itemPrice'));


		$this->smarty->assign('products', $products);
		$this->smarty->assign('properties', $properties);


		$this->smarty->assign('subCategoryKey', $param['subCategoryKey']);
		$dalObj = CategoryDAL::GetDalDataObj();
		$dalObj->addCondition('slug', $param['subCategoryKey']);
		$dalObj->addJoin('CategoryDescription', ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = 1)');
		$result = CategoryDAL::GetResult($dalObj);
		if (isset($result[0])) {
			$this->smarty->assign('subCategory', $result[0]);
			$this->smarty->assign('category', $result[0]->getParentCategoryObj());
		}
		$this->AddBreadCrumb(Utils::Translate('compare', Registry::Get('_user')) . ' ' . $result[0]->getCategoryDescription()->getName() . ' ' . $result[0]->getParentCategoryObj()->getCategoryDescription()->getName(), Router::GenerateUrl('current'));
		$this->AddTitle(Utils::Translate('compare', Registry::Get('_user')) . ' ' . $result[0]->getCategoryDescription()->getName() . ' ' . $result[0]->getParentCategoryObj()->getCategoryDescription()->getName());
		$this->AddDescription(Utils::Translate('compare', Registry::Get('_user')) . ' ' . $result[0]->getCategoryDescription()->getName() . ' ' . $result[0]->getParentCategoryObj()->getCategoryDescription()->getName());
	}

	public function AddToCompareAction($param) {
		header('Content-type: application/javascript');
		$this->SetAjaxRender();
		if (isset($param['productKey']) && isset($param['categoryKey']) && isset($param['subCategoryKey'])) {
			if (SessionProxy::IsSetValue('productCompareArray')) {
				$productCompareArray = SessionProxy::GetValue('productCompareArray');
				if (!is_array($productCompareArray))
					$productCompareArray = array();
			} else {
				$productCompareArray = array();
			}
			if (!isset($productCompareArray[$param['categoryKey']][$param['subCategoryKey']][$param['productKey']])) {
				if (!isset($productCompareArray[$param['categoryKey']][$param['subCategoryKey']]) || count($productCompareArray[$param['categoryKey']][$param['subCategoryKey']]) < 5) {
					$productCompareArray[$param['categoryKey']][$param['subCategoryKey']][$param['productKey']] = $param['productKey'];
					SessionProxy::ClearValue('productCompareArray');
					SessionProxy::SetValue('productCompareArray', $productCompareArray);
				} else {
					$this->smarty->assign('toManyProducts', true);
				}
			}

			$this->MyListContent($productCompareArray);
			// $this->content = $this->smarty->fetch('partial/Product/EmptyMyList.tpl');
		}
	}

	public function MyListContent($productCompareArray, $reload = false) {
		$values = Utils::GetArrayValuesRecursive($productCompareArray);

		if ($reload) {
			$this->smarty->assign('reloadLink', '');
		}

		$dalObj = ProductDAL::GetDalDataObj();
		$dalObj->addCondition('product.slug', '("' . implode('","', $values) . '")', ' IN ');
		$dalObj->addJoin('ProductDescription', ' LEFT JOIN product_description ON(product.id_product = product_description.id_product AND product_description.id_language = ' . Registry::Get('default_language_id') . ')');
		$dalObj->addJoin('Manufacturer', ' LEFT JOIN manufacturer ON (product.id_manufacturer = manufacturer.id_manufacturer AND manufacturer.active = 1)');
		$products0 = ProductDAL::GetResult($dalObj);

		$products = array();
		$p = 0;
		foreach ($products0 as $prod) {
			$products[$prod->getSlug()] = $prod;
			$p++;
		}

		foreach ($productCompareArray as $category => $cv) {
			$dalObj = CategoryDAL::GetDalDataObj();
			$dalObj->addJoin('CategoryDescription', ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = 1)');
			$dalObj->addCondition('slug', $category);
			$result = CategoryDAL::GetResult($dalObj);
			if (isset($result[0]))
				$productCompareArray[$category]['name'] = $result[0];

			foreach ($cv as $subCategory => $product) {
				$dalObj = CategoryDAL::GetDalDataObj();
				$dalObj->addJoin('CategoryDescription', ' LEFT JOIN category_description ON (category.id_category = category_description.id_category AND category_description.id_language = 1)');
				$dalObj->addCondition('slug', $subCategory);
				$result = CategoryDAL::GetResult($dalObj);
				if (isset($result[0]))
					$productCompareArray[$category]['values'][$subCategory]['name'] = $result[0];
				$compareLink = '';
				foreach ($product as $p => $v) {
					$productCompareArray[$category]['values'][$subCategory]['values'][$v] = $products[$v];
					$compareLink .='_' . $products[$v]->getId();
				}
				$productCompareArray[$category]['values'][$subCategory]['compareLink'] = $compareLink;

				if ($reload && $subCategory == $reload) {
					$this->smarty->assign('reloadLink', $compareLink);
					$this->smarty->assign('sck', $subCategory);
				}
			}
		}

		//var_dump($productCompareArray);
		//echo count($products);
//var_dump(count($products0));

		$count = count($products0);

		//if($count == ''){
		//	 $count = '0';
		// }


		$this->smarty->assign('myListNumProducts', $count);
		$this->smarty->assign('products', $productCompareArray);
		$this->smarty->assign('lang_id', Registry::Get('default_language_id'));
	}

	public function EmptyMyListAction($param) {
		header('Content-type: application/javascript');
		$this->SetAjaxRender();

		$productCompareArray = SessionProxy::GetValue('productCompareArray');
		if (is_array($productCompareArray)) {

			if (isset($_POST['subCategoryKey']) || isset($_POST['productKey'])) {

				foreach ($productCompareArray as $category => $sub) {
					if (isset($_POST['subCategoryKey']) && isset($productCompareArray[$category][$_POST['subCategoryKey']])) {
						unset($productCompareArray[$category][$_POST['subCategoryKey']]);
					}
					foreach ($sub as $key => $value) {
						//var_dump($productCompareArray[$category][$key][$_POST['productKey']]);
						//var_dump($value);
						if (isset($_POST['productKey']) && isset($productCompareArray[$category][$key][$_POST['productKey']])) {
							unset($productCompareArray[$category][$key][$_POST['productKey']]);
						}
						if (isset($productCompareArray[$category][$key])) {
							if (count($productCompareArray[$category][$key]) == 0) {
								unset($productCompareArray[$category][$key]);
							}
						}
					}
				}
			} else {
				$productCompareArray = array();
			}


			SessionProxy::ClearValue('productCompareArray');
			SessionProxy::SetValue('productCompareArray', $productCompareArray);

			$reload = false;

			if (isset($_POST['reload'])) {
				$reload = $_POST['reload'];
			}


			$this->MyListContent($productCompareArray, $reload);
		}
	}

	
	/**
	 * @todo nie wyciagac z bazy wszystkiego tylko id_product i name
	 **/
	public function AjaxRacquetFinderAction($param) {
		header('Content-type: application/javascript');
		$this->SetAjaxRender();
		$this->SetNoRender();
		$search_string = Request::Get('s', true);
		$arrSearch = explode(" ", $search_string);
		
		$dalObj = ProductDAL::GetDalDataObj();
		$dalObj->addJoin('ProductDescription',  'LEFT JOIN product_description ON(product.id_product = product_description.id_product AND product_description.id_language = ' . Registry::Get('default_language_id') . ')');
		$dalObj->addCondition('product.active', '1');
		
		foreach($arrSearch as $search_string) {
			$dalObj->addCondition('product.slug', '\'%' .$search_string . '%\'', 'LIKE');
		}
		$productObj = ProductDAL::GetResult($dalObj);
		
		$ret = array();
		foreach($productObj as $item) {
			$ret[$item->getId()] = $item->getProductDescription()->getName(); 
		}
		echo json_encode($ret);
	}
	
	/**
	 * Czesc wspolna wszystkich podstron
	 *
	 */
	public function PreDispatch($param) {

		$this->Run($param);
	}

	public function PostDispatch($param) {

		// nagłówek strony
		$this->RunShared('Header', $param);


		// footer
		$this->RunShared('Footer', $param);
	}

}

?>
